package com.v2future.sjt.collegecheckingattendance.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.JsResult;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;

public class ProgressWebView extends WebView {

    private ProgressBar progressbar;
    private Context mContext;

    @SuppressWarnings("deprecation")
    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        progressbar = new ProgressBar(context, null,
                android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                10, 0, 0));
        progressbar.setProgressDrawable(context.getResources().getDrawable(
                R.drawable.custom_web_progress_style));
        addView(progressbar);
        setWebChromeClient(new WebChromeClient());
    }

    public class WebChromeClient extends android.webkit.WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (((MainActivity) mContext).getTitleText().isEmpty()) {
                ((MainActivity) mContext).setTitleText(title);
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressbar.setVisibility(GONE);
            } else {
                if (progressbar.getVisibility() == GONE)
                    progressbar.setVisibility(VISIBLE);
                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
//            Intent loginIntent = new Intent(mContext, LoginActivity.class);
//            ((MainActivity) mContext).startActivityForResult(loginIntent, HandlerCASE.MSG_DONE);
//            result.cancel();
            return true;
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
        lp.x = l;
        lp.y = t;
        progressbar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }
}
